﻿namespace XRepair.WebCore.Authentication
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using XRepair.Conventions.Enum;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class xRepairAdminAuthorize : AuthorizeAttribute
    {
        public UserPermission RoleID { get; set; }

        private static readonly string _sessionRoleIdKey = "_userroleidsessionkey_";

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);

            if (!isAuthorized)
            {
                return false;
            }

            var contextSession = httpContext.Session;

            if (contextSession != null)
            {
                var roleIdInContext = contextSession[_sessionRoleIdKey];

                if (roleIdInContext != null)
                {
                    int roleIdValue = 99;

                    if (int.TryParse(roleIdInContext.ToString(), out roleIdValue))
                    {
                        // The greater, the weaker
                        return (roleIdValue <= Convert.ToInt32(RoleID));
                    }
                }
            }

            return false;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Session == null || filterContext.HttpContext.Session.Count == 0)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                        {
                            controller = "account",
                            action = "login"
                        })
                    );
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "error",
                                action = "irrelevant-access"
                            })
                        );
            }
        }
    }
}
